import React, {useState} from 'react';
import Brightness4Icon from '@material-ui/icons/Brightness4';
import Brightness7Icon from '@material-ui/icons/Brightness7';
import {makeStyles} from '@material-ui/core/styles';
import Box from "@material-ui/core/Box";
import LeftDrawer from "../Drawer/LeftDrawer";
import AppBar from "@material-ui/core/AppBar";
import Toolbar from "@material-ui/core/Toolbar";
import IconButton from "@material-ui/core/IconButton";
import Tooltip from "@material-ui/core/Tooltip";
import {useHistory} from 'react-router-dom';
import {useDispatch, useSelector} from "react-redux";
import {setLeftDrawerMenuIndex, setLightMode} from "../../../../../redux/reducers/commonSettings";
import SettingsIcon from '@material-ui/icons/Settings';
import Grid from "@material-ui/core/Grid";
import {
  Backdrop,
  CircularProgress,
  CssBaseline,
  Divider,
  Drawer,
  Hidden, ListItem,
  Menu,
  MenuItem,
  Typography,
  useTheme
} from "@material-ui/core";
import MenuIcon from "@material-ui/icons/Menu";
import Avatar from "@material-ui/core/Avatar";
import HelpOutlineIcon from '@material-ui/icons/HelpOutline';
import {getRandomColor, toFirstLetter} from "../../../../../assets/functions/functions";
import ListItemText from "@material-ui/core/ListItemText";
import ListItemIcon from "@material-ui/core/ListItemIcon";
import ExitToAppIcon from "@material-ui/icons/ExitToApp";
import {setActiveUser} from "../../../../../redux/reducers/userLogin";


const drawerWidth = 300;
let avatarColor = getRandomColor();
const useStyles = makeStyles((theme) => ({
  root: {
    display: "flex"
  },
  drawer: {
    [theme.breakpoints.up("md")]: {
      width: drawerWidth,
      flexShrink: 0
    },
  },
  appBar: {
    zIndex: 8,
    backgroundColor: theme.palette.type === 'light' ? theme.palette.common.white : theme.palette.grey[800],
  },
  menuButton: {
    [theme.breakpoints.up("md")]: {
      display: "none"
    },
    color: theme.palette.type === 'light' ? theme.palette.primary.dark : theme.palette.common.white,
  },
  toolbar: theme.mixins.toolbar,
  drawerPaper: {
    width: drawerWidth,
    zIndex: 7
  },
  buttonSettings: {
    color: theme.palette.type === 'light' ? theme.palette.primary.dark : theme.palette.common.white,
  },
  avatarName: {
    cursor: "pointer",
    backgroundColor: avatarColor,
    color: theme.palette.common.white,
    marginLeft: theme.spacing(3)
  },
  avatarProfile: {
    backgroundColor: avatarColor,
    color: theme.palette.common.white,
  },
  backdrop: {
    zIndex: theme.zIndex.drawer + 1,
    color: '#fff',
  },
}));

export default function EditorHeader() {
  // const login = !!localStorage.getItem('userToken');
  const history = useHistory();
  const classes = useStyles();
  const theme = useTheme();
  const dispatch = useDispatch();
  const darkMode = useSelector((state) => state.commonSettings.darkMode);
  const selectedIndex = useSelector((state) => state.commonSettings.leftDrawerMenuIndex);

  const [openLeftDrawer, setOpenLeftDrawer] = useState(false);
  const [openHelp, setOpenHelp] = useState(null);
  const [openProfile, setOpenProfile] = useState(null);
  const [loggingOut, setLoggingOut] = useState(false);
  const parsedUser = JSON.parse(localStorage.getItem('openlapUser'));
  const userName = toFirstLetter(parsedUser.firstname) + toFirstLetter(parsedUser.lastname);
  const welcome = parsedUser.firstname + " " + parsedUser.lastname;


  const setSelectedIndex = (value) => {
    dispatch(setLeftDrawerMenuIndex(value));
  }

  const openSettings = () => {
    setOpenProfile(null);
    setSelectedIndex(null);
    history.push('/settings');
  }

  const toggleDarkMode = () => {
    dispatch(setLightMode(!darkMode));
  }

  const toggleDrawer = () => {
    setOpenLeftDrawer(!openLeftDrawer);
  }

  const toggleHelpList = (e) => {
    setOpenHelp(e.currentTarget);
  }

  const toggleProfileList = (e) => {
    setOpenProfile(e.currentTarget);
  }

  const handleLogout = () => {
    setOpenProfile(null);
    setLoggingOut(!loggingOut);
    setTimeout(function () {
      window.location.href = "/";
      localStorage.clear()
      dispatch(setLightMode(false));
      dispatch(setActiveUser());
    }, 1000)
  }

  return (
    <>
      <CssBaseline/>

      <AppBar position="fixed" className={classes.appBar}>
        <Toolbar>
          <IconButton
            aria-label="open drawer"
            edge="start"
            onClick={toggleDrawer}
            className={classes.menuButton}
          >
            <MenuIcon/>
          </IconButton>

          <Grid container alignItems="center">

            {/* Logo */}
            <Grid item xs>
              {darkMode ? <img src={"/images/openlapDarkTheme.svg"} height='38' alt="Dark Theme Logo"/> :
                <img src={"/images/openlapLightTheme.svg"} height='38' alt="Light Theme Logo"/>}
            </Grid>

            {/* Help button */}
            <Grid item>
              <Tooltip arrow title="Support">
                <IconButton color='inherit' className={classes.buttonSettings} onClick={toggleHelpList}>
                  <HelpOutlineIcon/>
                </IconButton>
              </Tooltip>

              <Menu
                id="simple-menu"
                anchorEl={openHelp}
                getContentAnchorEl={null}
                anchorOrigin={{vertical: "bottom", horizontal: "right"}}
                transformOrigin={{vertical: "top", horizontal: "right"}}
                open={Boolean(openHelp)}
                onClose={() => setOpenHelp(null)}
              >
                <MenuItem>
                  <ListItemText primary='Tour' secondary="Start here for a quick overview of OpenLAP"/>
                </MenuItem>
                <MenuItem>
                  <ListItemText primary='FAQ' secondary="Frequently Asked Questions"/>
                </MenuItem>
                <Divider/>
                <MenuItem>
                  <ListItemText primary='Feedback' secondary="Send your opinions about our platform"/>
                </MenuItem>
              </Menu>
            </Grid>

            {/* Toggle Light/Dark mode button */}
            <Grid item>
              <Tooltip arrow title="Toggle light/dark theme">
                <IconButton color='inherit' className={classes.buttonSettings} onClick={toggleDarkMode}>
                  {darkMode ? <Brightness7Icon/> : <Brightness4Icon/>}
                </IconButton>
              </Tooltip>
            </Grid>


            {/* Avatar to show username*/}
            <Grid item>
              <Avatar className={classes.avatarName} onClick={toggleProfileList}>
                {userName}
              </Avatar>

              <Menu
                id="simple-menu"
                anchorEl={openProfile}
                getContentAnchorEl={null}
                anchorOrigin={{vertical: "bottom", horizontal: "right"}}
                transformOrigin={{vertical: "top", horizontal: "right"}}
                open={Boolean(openProfile)}
                onClose={() => setOpenProfile(null)}
              >
                <ListItem>
                  <ListItemIcon>
                    <Avatar className={classes.avatarProfile}>
                      {userName}
                    </Avatar>
                  </ListItemIcon>
                  <ListItemText primary={<b>{welcome}</b>}/>
                </ListItem>

                <Divider/>
                <MenuItem onClick={openSettings}>
                  <ListItemIcon> <SettingsIcon/> </ListItemIcon>
                  <ListItemText primary='Settings'/>
                </MenuItem>

                <Divider/>
                <MenuItem onClick={handleLogout}>
                  <ListItemIcon> <ExitToAppIcon/> </ListItemIcon>
                  <ListItemText primary='Sign-out'/>
                </MenuItem>
              </Menu>
            </Grid>

          </Grid>

        </Toolbar>

      </AppBar>


      <Box className={classes.drawer} aria-label="side panel">
        <Hidden mdUp implementation="css">
          <Drawer
            variant="temporary"
            anchor={theme.direction === "rtl" ? "right" : "left"}
            open={openLeftDrawer}
            onClose={toggleDrawer}
            classes={{paper: classes.drawerPaper}}
            ModalProps={{keepMounted: true}}
          >
            <LeftDrawer selectedIndex={selectedIndex} setSelectedIndex={setSelectedIndex}/>
          </Drawer>
        </Hidden>
        <Hidden smDown implementation="css">
          <Drawer
            classes={{
              paper: classes.drawerPaper
            }}
            variant="permanent"
            open
          >
            <LeftDrawer selectedIndex={selectedIndex} setSelectedIndex={setSelectedIndex}/>
          </Drawer>
        </Hidden>
      </Box>

      {/* Animation for logging out*/}
      <Backdrop className={classes.backdrop} open={loggingOut}>
        <Grid container direction="column" justify="center" alignItems="center">
          <Grid item>
            <CircularProgress color="inherit"/>
          </Grid>
          <Grid item>
            <Typography>Logging out</Typography>
          </Grid>
        </Grid>
      </Backdrop>
    </>
  );
}
